package com.mqqzt.douban;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gdata.data.Link;
import com.google.gdata.data.douban.Attribute;
import com.google.gdata.data.douban.CollectionEntry;
import com.google.gdata.data.douban.CollectionFeed;
import com.google.gdata.data.douban.Subject;
import com.google.gdata.data.douban.UserEntry;
import com.google.gdata.data.extensions.Rating;
import com.mqqzt.douban.domain.Book;
import com.mqqzt.douban.util.LoadImageAsyncTask;
import com.mqqzt.douban.util.LoadImageAsyncTask.LoadImageCallback;

public class MyReadActivity extends BaseActivity implements OnItemClickListener, OnClickListener {
	private ListView subjectlist;
	private MyReaderAdapter adapter;
	private Map<String, SoftReference<Bitmap>> iconCache;
	private int startIndex;
	private int count;
	private boolean isLoading = false;
	private KillReceiver receiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.subject);
		super.onCreate(savedInstanceState);
		iconCache = new HashMap<String, SoftReference<Bitmap>>();
		startIndex = 1;
		count = 5;
	}
	@Override
	public void setupView() {
		subjectlist = (ListView) this.findViewById(R.id.subjectlist);
		mTextViewTitle = (TextView) this.findViewById(R.id.myTitle);
		mRelativeLayoutLoading = (RelativeLayout) this.findViewById(R.id.loading);
		mImageBack = (ImageButton) this.findViewById(R.id.back_button);
		receiver = new KillReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("kill_activity_action");
		this.registerReceiver(receiver, filter);

	}

	@Override
	public void setListener() {
		subjectlist.setOnItemClickListener(this);
		mImageBack.setOnClickListener(this);
		subjectlist.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					int position = view.getLastVisiblePosition();
					int totalCount = subjectlist.getCount();
					if(position == (totalCount - 1)){
						startIndex = startIndex + count;
						if(isLoading){
							return;
						}
						fillData();
					}
					break;

				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public void fillData() {
		mTextViewTitle.setText("我读");
		new AsyncTask<Void, Void, List<Book>>() {
			
			@Override
			protected void onPreExecute() {
				showLoading();
				isLoading = true;
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(List<Book> result) {
				hideLoading();
				if(result != null){
					if(adapter == null){
						adapter = new MyReaderAdapter(result);
						subjectlist.setAdapter(adapter);
					}else{
						adapter.addMoreBook(result);
						adapter.notifyDataSetChanged();
					}
					
					
				}else{
					Toast.makeText(MyReadActivity.this, "获取服务器数据失败", Toast.LENGTH_LONG).show();
				}
				isLoading = false;
				super.onPostExecute(result);
			}

			@Override
			protected List<Book> doInBackground(Void... params) {
				try {
					UserEntry ue = myService.getAuthorizedUser();
					String uid = ue.getUid();
					CollectionFeed feeds = myService.getUserCollections(uid, null, null,
							null, startIndex, count);
					List<Book> books = new ArrayList<Book>();
					for (CollectionEntry ce : feeds.getEntries()) {
						Subject se = ce.getSubjectEntry();
						if (se == null)
							return null;
						Book book = new Book();
						List<Link> links = se.getLinks();
						for (Link link : links) {
							if ("image".equals(link.getRel())) {
								String path = link.getHref();
								book.setBookurl(path);
							}
						}
						String title = se.getTitle().getPlainText();
						book.setName(title);
						StringBuilder sb = new StringBuilder();
						for (Attribute attr : se.getAttributes()) {
							if ("author".equals(attr.getName())) {
								String author = attr.getContent();
								sb.append(author);
								sb.append("/");
							} else if ("publisher".equals(attr.getName())) {
								String publisher = attr.getContent();
								sb.append(publisher);
								sb.append("/");
							} else if ("pubdate".equals(attr.getName())) {
								String pubdate = attr.getContent();
								sb.append(pubdate);
								sb.append("/");
							} else if ("isbn10".equals(attr.getName())) {
								String isbn10 = attr.getContent();
								sb.append(isbn10);
								sb.append("/");
							}
							book.setDescription(sb.toString());
						
							Rating rating = se.getRating();
							if (rating != null)
								book.setRating(rating.getAverage());
							
						}
						books.add(book);
					}
					
					return books;
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
				
			}
		}.execute();

	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Book book = (Book) subjectlist.getItemAtPosition(position);
		String description = book.getDescription();
		String isbn = description.substring(0, description.indexOf("/"));
		Intent intent = new Intent(this, BookDetailActivity.class);
		intent.putExtra("isbn", isbn);
		startActivity(intent);
		
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_button:
			finish();
			break;

		}
		
	}
	
	private class MyReaderAdapter extends BaseAdapter{
		private List<Book> books;
		
		public MyReaderAdapter(List<Book> books) {
			this.books = books;
		}
		
		public void addMoreBook(List<Book> books){
			for(Book book : books){
				this.books.add(book);
			}
		}

		@Override
		public int getCount() {
			return books.size();
		}

		@Override
		public Object getItem(int position) {
			return books.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = View.inflate(MyReadActivity.this, R.layout.book_item, null);
			final ImageView iv_book = (ImageView) view.findViewById(R.id.book_img);
			RatingBar rb = (RatingBar) view.findViewById(R.id.ratingbar);
			TextView tv_title = (TextView) view.findViewById(R.id.book_title);
			TextView tv_description = (TextView) view.findViewById(R.id.book_description);
			
			Book book = books.get(position);
			if(book.getRating() == 0){
				rb.setVisibility(View.INVISIBLE);
			}else{
				rb.setRating(book.getRating());
			}
			tv_title.setText(book.getName());
			tv_description.setText(book.getDescription());
			String iconpath = book.getBookurl();
			final String iconname = iconpath.substring(iconpath.lastIndexOf("/") + 1, iconpath.length());
			/*File file = new File("/mnt/sdcard/" + iconname);
			if(file.exists()){
				iv_book.setImageURI(Uri.fromFile(file));
				System.out.println("使用SD卡缓存");*/
			if(iconCache.containsKey(iconname)){
				SoftReference<Bitmap> softref = iconCache.get(iconname);
				if(softref != null){
					Bitmap bitmap = softref.get();
					if(bitmap != null){
						iv_book.setImageBitmap(bitmap);
						System.out.println("使用内存缓存");
					}else{
						loadImage(iv_book, book, iconname);
					}
				}
			}else{
				loadImage(iv_book, book, iconname);
			}
			
			return view;
		}

		private void loadImage(final ImageView iv_book, Book book,
				final String iconname) {
			LoadImageAsyncTask task = new LoadImageAsyncTask(new LoadImageCallback() {
				
				@Override
				public void beforeLoadImage() {
					iv_book.setImageResource(R.drawable.book);
					
				}
				
				@Override
				public void afterLoadImage(Bitmap bitmap) {
					if(bitmap != null){
						iv_book.setImageBitmap(bitmap);
						System.out.println("下载服务器图片");
						/*File file = new File("/mnt/sdcard/" + iconname);
						FileOutputStream stream;
						try {
							stream = new FileOutputStream(file);
							bitmap.compress(CompressFormat.JPEG, 100, stream);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}*/
						iconCache.put(iconname, new SoftReference<Bitmap>(bitmap));
						
					}else{
						iv_book.setImageResource(R.drawable.book);
					}
					
				}
			});
			task.execute(book.getBookurl());
		}
		
	}
	
	private class KillReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			iconCache = null;
			Toast.makeText(MyReadActivity.this, "内存不足，程序退出", Toast.LENGTH_LONG).show();
			finish();
			
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(receiver);
	}
}
